<?php
/**
 * Created by PhpStorm.
 * User: 沁塵
 * Date: 2019/4/20
 * Time: 19:57
 */

namespace app\api\controller\v1;

use app\api\model\Service;
use app\api\model\ServiceDis;
use app\api\service\token\LoginToken;
use think\Request;


class Bd
{

    public function takePicture()
    {
        //token如果过期了，去 https://dev2.baidu.com/appmanage 这边拿最新的 账号 壮壮本地生活  密码 Cjw123456
//        $client_id = "58abed219e625010c562ec2ba1ae663f";
//        $client_secret = "d9f0a711b2b1e089c1a41c39fb492e2e";
        $token = 'eyJhbGciOiJIUzM4NCJ9.eyJzdWIiOiJhY2MiLCJhdWQiOiLnp43ojYnlsI_ngavnrq0iLCJ1aWQiOjYxMTI3NjA3LCJhcHBJZCI6IjU4YWJlZDIxOWU2MjUwMTBjNTYyZWMyYmExYWU2NjNmIiwiaXNzIjoi5ZWG5Lia5byA5Y-R6ICF5Lit5b-DIiwicGxhdGZvcm1JZCI6IjQ5NjAzNDU5NjU5NTg1NjE3OTQiLCJleHAiOjQxMDI0MTYwMDAsImp0aSI6IjkxODAzMTE5NjYwNjYzNDM5NDMifQ.uYsYHjRKC_-TyWuAQOKErqJlTaKaKFWChYoPRPD42tuxQhfm17PSl5ZBoIR8EmYM';

        $uploadUrl = "https://api.baidu.com/json/sms/service/ImageManageService/uploadImage";
        $url = $_FILES['file']['tmp_name'];
//        return $filePath;
//        $url = 'C:\Users\Administrator\Desktop\c2524741b4dc3b44a1ccbe7c7eb139d.png';
        $data = [
            'header'=>[
                'accessToken' => $token,
                'userName' => '壮壮本地生活'
            ],
            'body'=>[
                'items' => [[
                    "content"=>base64_encode(file_get_contents($url)),
                    "imgmd5"=>md5_file($url),
                    "imageName"=>'c2524741b4dc3b44a1ccbe7c7eb139d'
                ]],
                "addImage" => true
            ],
        ];
        $res = curlPost($uploadUrl,json_encode($data));
        return json_encode(['code'=>0,'msg'=>'','data'=> ['src'=>$res['body']['data'][0]['url']]]);

    }


    public function getCategory(Request $request) {
        $category = [
            [
                "id" => 30829,
                "name" => "房产家居",
                "child" => [
                    [
                        "id" => 30876,
                        "name" => "装修建材"
                    ]
                ]
            ],
            [
                "id" => 30537,
                "name" => "交通出行",
                "child" => [
                    [
                        "id" => 30655,
                        "name" => "汽配及服务",
                        "child" => [
                            [
                                "id" => 30656,
                                "name" => "汽车配件"
                            ]
                        ]
                    ],
                    [
                        "id" => 30721,
                        "name" => "摩托车"
                    ],
                    [
                        "id" => 30797,
                        "name" => "车辆平台",
                        "child" => [
                            [
                                "id" => 30802,
                                "name" => "汽车电商"
                            ]
                        ]
                    ]
                ]
            ],
            [
                "id" => 24151,
                "name" => "生活服务",
                "child" => [
                    [
                        "id" => 38665,
                        "name" => "宠物服务"
                    ],
                    [
                        "id" => 38664,
                        "name" => "心理援助"
                    ],
                    [
                        "id" => 43906,
                        "name" => "养生保健"
                    ],
                    [
                        "id" => 38662,
                        "name" => "摄影婚庆"
                    ],
                    [
                        "id" => 43913,
                        "name" => "生活美容",
                        "child" => [
                            [
                                "id" => 43914,
                                "name" => "美发"
                            ],
                            [
                                "id" => 43921,
                                "name" => "彩妆造型"
                            ],
                            [
                                "id" => 43922,
                                "name" => "美体"
                            ],
                            [
                                "id" => 43919,
                                "name" => "美甲"
                            ],
                            [
                                "id" => 43929,
                                "name" => "皮肤美容"
                            ],
                        ]
                    ],
                ]
            ],
            [
                "id" => 43988,
                "name" => "休闲娱乐",
                "child" => [
                    [
                        "id" => 43989,
                        "name" => "室内娱乐"
                    ]
                ]
            ]
        ];
        return writeJson(200, $category, '获取类目');
    }

    public function pubPicture(Request $request)
    {
        //token如果过期了，去 https://dev2.baidu.com/appmanage 这边拿最新的 账号 壮壮本地生活  密码 Cjw123456
        $token = 'eyJhbGciOiJIUzM4NCJ9.eyJzdWIiOiJhY2MiLCJhdWQiOiLnp43ojYnlsI_ngavnrq0iLCJ1aWQiOjYxMTI3NjA3LCJhcHBJZCI6IjU4YWJlZDIxOWU2MjUwMTBjNTYyZWMyYmExYWU2NjNmIiwiaXNzIjoi5ZWG5Lia5byA5Y-R6ICF5Lit5b-DIiwicGxhdGZvcm1JZCI6IjQ5NjAzNDU5NjU5NTg1NjE3OTQiLCJleHAiOjQxMDI0MTYwMDAsImp0aSI6IjkxODAzMTE5NjYwNjYzNDM5NDMifQ.uYsYHjRKC_-TyWuAQOKErqJlTaKaKFWChYoPRPD42tuxQhfm17PSl5ZBoIR8EmYM';
        $uploadUrl = "https://api.baidu.com/json/sms/service/LocalContentService/saveContent";
        $params = $request->post();
//        $params = [
//            "coverImages" => [
//                "['https://pic.rmb.bdstatic.com/bjh/240611/dump/3068cf6364b636c6be0b688deb2f4d60.jpeg','https://pic.rmb.bdstatic.com/bjh/240611/dump/734fa7a1a30f83146980fa6e049ea49d.jpeg','https://pic.rmb.bdstatic.com/bjh/240611/dump/7cb470986a3653e9622141f5c666eb71.jpeg']"
//            ],
//            "content" => "<p class=\"pgc-h-arrow-right\"><span></span><strong><span style=\"color: #FFBA12;--tt-darkmode-color: #DEA210\">浙江那边有一户人家火了，拒绝过度装修，全屋那叫一个高级，忍不住晒晒</span></strong><span>，下面一起看看吧。</span></p><img style=\"display: block;\" src=\"https://pic.rmb.bdstatic.com/bjh/240611/dump/3068cf6364b636c6be0b688deb2f4d60.jpeg\"><h3 class=\"pgc-h-arrow-right\">小客厅</h3><p class=\"pgc-p\"><span>在</span><strong><span style=\"color: #FFBA12;--tt-darkmode-color: #DEA210\">对餐厅旁的一个房间进行拆除后，原本的餐厅被巧妙地改造成一个温馨的小客厅</span></strong><span>，这样的设计不仅优化了空间利用，还为家庭生活增添了更多的活动区域。</span></p><p class=\"pgc-p\">小客厅与餐厅之间安装了一小截玻璃隔断，使得两个空间既有独立性，又保持了视觉上的通透感。</p><img style=\"display: block;\" src=\"https://pic.rmb.bdstatic.com/bjh/240611/dump/734fa7a1a30f83146980fa6e049ea49d.jpeg\"><p class=\"pgc-p\">小客厅，是家中的一处温馨角落，一片属于家人们轻松娱乐的天地。在这个小而精致的空间里，摆放着一个超级小巧的沙发，仿佛是为了迎合每一次闲暇时光的柔软呼唤。</p><p class=\"pgc-p\"><strong><span style=\"color: #FFBA12;--tt-darkmode-color: #DEA210\">沙发的设计别出心裁，小巧玲珑却蕴含着无限的温馨</span></strong><span>，它的每一寸布料似乎都沉醉在岁月的轻柔中，轻抚之下仿佛能感受到岁月静好的味道。</span></p><p class=\"pgc-p\"><span>沙发的旁边，</span><strong><span style=\"color: #FFBA12;--tt-darkmode-color: #DEA210\">摆放着一张小小的圆形地毯</span></strong><span>，精致的图案渐次展开，如同一幅缓缓绽放的画卷，将温暖与美好渲染于每一寸空间。</span></p><img style=\"display: block;\" src=\"https://pic.rmb.bdstatic.com/bjh/240611/dump/7cb470986a3653e9622141f5c666eb71.jpeg\"><p class=\"pgc-p\">地毯的柔软触感仿佛是一道亲切的拥抱，让人沉浸在无尽的舒适中。坐在小沙发上，脚底踏着地毯的柔软，仿佛是在走进一个温馨的梦境，一切烦恼和忧愁都被柔软的温暖吞噬。</p><p class=\"pgc-p\"><strong><span style=\"color: #FFBA12;--tt-darkmode-color: #DEA210\">小沙发的另一个魅力，是它隐藏的身份——一个可变形的沙发床</span></strong><span>。",
//        ];
        $local = $params;
        $coverImages = '[';

        $content = $params['content'];
        preg_match_all('/https?:\/\/[^\s]+/', $content, $matches);

        $urls = $matches[0];
        foreach ($urls as $url) {
            $url = substr($url, 0, -1);
            if ($coverImages != '[') {
                $coverImages .= ',';
            }
            $coverImages .= "'".$url."'";
        }
        $coverImages .= ']';
        $local['coverImages'] = $coverImages;
        $local["detailCategory"] = json_encode([
//            "id" => 0,
            "name" => $params['oneCate'],
            "child" => [
//                "id" => 0,
                "name" => $params['twoCate']
            ],
        ], 360);
        $local["status"] = 0;
        $res = Service::create($local);
        $data = [
            'header'=>[
                'accessToken' => $token,
                'userName' => '壮壮本地生活'
            ],
            'body'=>[
                "sourceName" => "福建一诗二画信息科技有限公司",
                "authorName" => $local['authorName'],  //作者名称
                "avatar" => $local['avatar'], //头像地址
                "publishAt" => round(microtime(true) * 1000),
                "isDelete" => 0,
                "nid" => $res['id'],
                "title" => $local['title'],
                "summary" => $local['summary'],
                "coverImages" => [$coverImages],
                "originalUpdateTime" => round(microtime(true) * 1000),
                "contentUrl" => "",
                "content" => $local['content'],
                "detailCategory" => [
//                    "id" => 30829,
                    "name" => $params['oneCate'],
                    "child" => [
//                        "id" => 30876,
                        "name" => $params['twoCate']
                    ],
                ],
            ],
        ];

        $result = curlPost($uploadUrl,json_encode($data));

        if ($result['header']['desc'] == 'success') {
            Service::where('id',$res['id'])->update(['status'=>1,'contentId'=>$result['body']['data'][0]['contentId']]);
            return ['code'=>200,'contentId'=>$result['body']['data'][0]['contentId'],'msg'=>'发布成功'];
        } else {
            Service::where('id',$res['id'])->update(['status'=>2,'remark'=>$result['header']['failures'][0]['message']]);
            return ['code'=>400,'msg'=>$result['header']['failures'][0]['message']];
        }
    }

    public function create(Request $request)
    {
        $params = $request->post();

        $res = ServiceDis::create($params);
        return writeJson(200,$res,'完成！');

    }

    public function disPull(Request $request)
    {
        $uid = LoginToken::getInstance()->getCurrentUid()??"";

        $item = ServiceDis::where(function ($q) {
                $q->where('status', 21)
                    ->whereOr('status', 22);
            })
            ->where(function ($q){
                $ten_min_ago = date("Y-m-d H:i:s", time() - 960);
                $q->whereNull('pull_time')->whereOr('pull_time','<',$ten_min_ago);

            })->findOrEmpty();

        if (!$item->isEmpty()) {
            $item->pull_time = Date("y-m-d H:i:s");
            $item->uid = $uid;
            $item->status = 22;
            $item->save();
        }

        return writeJson(200,$item,'拉取成功！');
    }

    public function rewrite(Request $request){
        $params = $request->post();

        $Event = ServiceDis::where('id',$params['id'])->findOrEmpty();
        if (!$Event->isEmpty()){
            $params['pub_time'] = date('Y-m-d H:i:s',time());
            $Event->save($params);
        }
        return writeJson(200,true,'回填成功！');

    }
    public function check(Request $request) {
        $params = $request->post();
        $event = new ServiceDis();
        $count = $event->where("title", $params["title"])->count();
        if ($count == 0) {
            return writeJson(200, false, '请求成功');
        } else {
            return writeJson(200, true, '请求成功');
        }

    }

}